import argparse
# import os
# import sys
import torch
from exp.exp_main import Exp_Main
import random
import numpy as np
# import pandas as pd
# import os


# MS:多信道预测单信道时，输出最后一个信道信息
def main():
    fix_seed = 1003
    random.seed(fix_seed)
    torch.manual_seed(fix_seed)
    np.random.seed(fix_seed)

    parser = argparse.ArgumentParser(description='Transformer family for Time Series Forecasting')

    # basic config
    parser.add_argument('--is_training', type=int, default=1, help='status')
    parser.add_argument('--model_id', type=str, default='test', help='model id')
    parser.add_argument('--model', type=str, default='LSTM_S2S',
                        help='model name, options: [A_BiLSTM, CNN_BiLSTM, iTransformer, LSTM_S2S_channel_batch]')

    # data loader
    parser.add_argument('--data', type=str, default='spectrum', help='dataset type')
    parser.add_argument('--root_path', type=str, default='./datas/', help='root path of the data file')
    parser.add_argument('--data_path', type=str, default='Spectrum.csv', help='data file')
    parser.add_argument('--features', type=str, default='S',
                        help='forecasting task, options:[M, S, MS, CMD_MS, CMD_MSall];' 
                             'M:multivariate predict multivariate;'
                             'S:univariate predict univariate;'
                             'MS:multivariate predict univariate')
    parser.add_argument('--target', type=int, default=0, help='target feature in S or MS task')
    parser.add_argument('--checkpoints', type=str, default='./checkpoints/', help='location of model checkpoints 结果保存位置')

    # forecasting task
    parser.add_argument('--seq_len', type=int, default=3, help='input sequence length')
    parser.add_argument('--label_len', type=int, default=0, help='start token length')
    parser.add_argument('--pred_len', type=int, default=1, help='prediction sequence length')

    # model define
    parser.add_argument('--enc_in', type=int, default=1, help='encoder input size')
    parser.add_argument('--dec_in', type=int, default=1, help='decoder input size')
    parser.add_argument('--c_out', type=int, default=1, help='output size')
    parser.add_argument('--d_model', type=int, default=512, help='dimension of model')
    parser.add_argument('--n_heads', type=int, default=8, help='num of heads') # n_heads = 4 for Crossformer
    parser.add_argument('--e_layers', type=int, default=1, help='num of encoder layers') # e_layers == 3 for Crossformer
    parser.add_argument('--d_layers', type=int, default=1, help='num of decoder layers')
    parser.add_argument('--d_ff', type=int, default=2048, help='dimension of fcn')
    parser.add_argument('--moving_avg', default=[24], help='window size of moving average')
    parser.add_argument('--factor', type=int, default=1, help='attn factor')
    parser.add_argument('--distil', action='store_false',
                        help='whether to use distilling in encoder, using this argument means not using distilling', # 在编码器中是否使用蒸馏，使用此参数意味着不蒸馏
                        default=True)
    parser.add_argument('--dropout', type=float, default=0.05, help='dropout') # dropout == 0.2 for ETSformer & Crossformer
    parser.add_argument('--embed', type=str, default='timeF',
                        help='time features encoding, options:[timeF, fixed, learned]')
    parser.add_argument('--activation', type=str, default='gelu', help='activation')  # activation == 'sigmoid' for ETSformer
    parser.add_argument('--output_attention', action='store_true', help='whether to output attention in encoder')
    parser.add_argument('--do_predict', action='store_true', help='whether to predict unseen future data')
    
    # optimization
    parser.add_argument('--num_workers', type=int, default=0, help='data loader num workers')  # 数据加载器的工作数
    parser.add_argument('--itr', type=int, default=1, help='experiments times')  # train次数
    parser.add_argument('--train_epochs', type=int, default=100, help='train epochs')
    parser.add_argument('--batch_size', type=int, default=32, help='batch size of train input data')
    parser.add_argument('--patience', type=int, default=10, help='early stopping patience')
    parser.add_argument('--learning_rate', type=float, default=0.0001, help='optimizer learning rate')
    parser.add_argument('--des', type=str, default='test', help='exp description')
    parser.add_argument('--loss', type=str, default='mse', help='loss function')
    # lradj == 'exponential_with_warmup' for ETSformer
    parser.add_argument('--lradj', type=str, default='type1', help='adjust learning rate')
    parser.add_argument('--use_amp', action='store_true', help='use automatic mixed precision training', default=False)
    

    # GPU
    parser.add_argument('--use_gpu', type=bool, default=True, help='use gpu')
    parser.add_argument('--gpu', type=int, default=0, help='gpu')
    parser.add_argument('--use_multi_gpu', action='store_true', help='use multiple gpus', default=False)
    parser.add_argument('--devices', type=str, default='0', help='device ids of multi gpus')

    # 模型训练/测试设置
    parser.add_argument('--run_train', action='store_true')  # 是否训练
    parser.add_argument('--run_test', action='store_true')  # 是否测试

    # RevIN
    parser.add_argument('--add_revin', action='store_true')  # whether to use RevIN  # 是否使用RevIN
    parser.add_argument('--revin_affine', action='store_true', help='whether to use RevIN affine')
    parser.add_argument('--subtract_last', action='store_true') # whether to subtract last

    # model 
    parser.add_argument('--fine_tuning', action='store_true', help='whether to fine-tuning') 
    parser.add_argument('--full_model', action='store_true', help='whether to fine-tune full model')


    args = parser.parse_args()

    args.use_gpu = True if torch.cuda.is_available() and args.use_gpu else False

    # 如果用GPU且用多GPU，则将args.gpu设置为多个GPU的第一个
    if args.use_gpu and args.use_multi_gpu:
        args.dvices = args.devices.replace(' ', '')  # 移除空格
        device_ids = args.devices.split(',')  # 以逗号分隔
        args.device_ids = [int(id_) for id_ in device_ids]  # 将字符串转换为整数
        args.gpu = args.device_ids[0]  # 选择第一个GPU

    print('Args in experiment:')
    print(args)

    for channel in [0]:
        args.target = channel

        for i in [4]:
            args.seq_len = i
            args.label_len = i//2
            Exp = Exp_Main
            if args.is_training:
                for ii in range(args.itr):
                    print(f"-------Start iteration {ii+1}--------------------------")
                    # setting record of experiment
                    setting = '{}_{}_Revin-{}-affine-{}-subtract_last-{}_feature-{}-{}_CMDfrom-{}_num{}_fine_tuing-{}_full_model-{}_full_datas{}'.format(
                        args.model,
                        args.data,
                        args.add_revin,
                        args.revin_affine,
                        args.subtract_last,
                        args.features,
                        args.target,
                        args.CMD_from,
                        args.CMD_num,
                        args.fine_tuning,
                        args.full_model,
                        args.full_datas
                       )

                    exp = Exp(args)  # set experiments
                    if args.run_train:
                        print('>>>>>>>start training : {}>>>>>>>>>>>>>>>>>>>>>>>>>>'.format(setting))
                        exp.train(setting)

                    if args.run_test:
                        print('>>>>>>>normal testing : {}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<'.format(setting))
                        # exp.test(setting, flag="test")
                        exp.test(setting, test=1, flag="test")



                    torch.cuda.empty_cache()

            else:
                ii = 0
                setting = '{}_{}_Revin-{}-affine-{}-subtract_last-{}_feature-{}-{}_CMDfrom-{}_num{}_fine_tuing-{}_full_model-{}_full_datas{}'.format(
                        args.model,
                        args.data,
                        args.add_revin,
                        args.revin_affine,
                        args.subtract_last,
                        args.features,
                        args.target,
                        args.CMD_from,
                        args.CMD_num,
                        args.fine_tuning,
                        args.full_model,
                        args.full_datas
                       )
                model_setting = '{}_{}_Revin-{}-affine-{}-subtract_last-{}_feature-{}-{}_CMDfrom-{}_num{}_fine_tuing-{}_full_model-{}_full_datas{}'.format(
                        args.model,
                        args.data,
                        args.add_revin,
                        args.revin_affine,
                        args.subtract_last,
                        args.features,
                        args.target,
                        args.CMD_from,
                        args.CMD_num,
                        False,
                        False,
                        False
                       )

                exp = Exp(args)  # set experiments
                if args.fine_tuning:
                    if args.full_model:
                        exp.test_fine_tuning_full_model(setting=setting, model_setting=model_setting)
                    else:
                        exp.test_fine_tuning_last_layer(setting=setting, model_setting=model_setting)
                else:
                    exp.test(setting, test=1)
                print('>>>>>>>testing : {}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<'.format(setting))
                torch.cuda.empty_cache()
            
            
        del exp

if __name__ == "__main__":
    main()
    